import Instance from './Instance';

export interface INumberUtils {
    computePercent(c: number, t: number, d?: number): number; //计算百分比
    randomLimit(s: number, e: number): number; //范围随机数
    randomArray<T>(ary: T[]): T; //随机数组中的一个元素
}

export class NumberUtils implements INumberUtils {
    public static getInstance(): NumberUtils {
        return Instance.get<NumberUtils>(NumberUtils);
    }

    computePercent(c: number, t: number, d?: number): number {
        const value = ((c / t) * 100).toFixed(d || 0);
        return +value;
    }

    randomLimit(s: number, e: number): number {
        s = Math.min(s, e);
        e = Math.max(s, e);
        const r = e - s;
        return s + Math.random() * r;
    }

    randomArray<T>(ary: T[]): T {
        if (!ary) return null;
        const index = Math.floor(Math.random() * ary.length);
        return ary[index];
    }
}
